package com.common.shiro.dao;

import com.common.constants.ShiroConstant;
import com.common.utils.JDKSerializeUtils; // 引入自定义JDK序列化工具类
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.UnknownSessionException;
import org.apache.shiro.session.mgt.SimpleSession;
import org.apache.shiro.session.mgt.eis.AbstractSessionDAO;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;

@Slf4j
public class RedisSessionDAO extends AbstractSessionDAO {

    @Resource
    private RedisTemplate<Object, Object> redisTemplate;

    // 仅保留Key的字符串序列化器（Value的序列化改用自定义工具类）
    private final StringRedisSerializer keySerializer = new StringRedisSerializer();

    @Override
    protected Serializable doCreate(Session session) {
        log.info("RedisSessionDAO - doCreate");
        // 生成SessionId
        Serializable sessionId = generateSessionId(session);
        // 把Session和sessionId关联起来
        assignSessionId(session, sessionId);
        // 保存Session到Redis
        saveSession(sessionId, session);
        return sessionId;
    }

    @Override
    protected Session doReadSession(Serializable sessionId) {
        log.info("RedisSessionDAO - doReadSession");
        if (sessionId == null) {
            return null;
        }
        Session session = getSession(sessionId);
        if (session != null) {
            // 刷新过期时间
            refreshSessionExpire(sessionId);
        }
        return session;
    }

    @Override
    public void update(Session session) throws UnknownSessionException {
        log.info("RedisSessionDAO - update");
        if (session == null || session.getId() == null) {
            return;
        }
        saveSession(session.getId(), session);
    }

    @Override
    public void delete(Session session) {
        log.info("RedisSessionDAO - delete");
        if (session == null || session.getId() == null) {
            return;
        }
        redisTemplate.execute((RedisCallback<Void>) connection -> {
            byte[] keyBytes = buildKeyBytes(session.getId());
            connection.del(keyBytes);
            return null;
        });
    }

    @Override
    public Collection<Session> getActiveSessions() {
        log.info("RedisSessionDAO - getActiveSessions");
        Set<byte[]> keyBytesSet = redisTemplate.execute((RedisCallback<Set<byte[]>>) connection ->
                connection.keys(buildKeyPatternBytes())
        );

        if (keyBytesSet == null || keyBytesSet.isEmpty()) {
            return new ArrayList<>();
        }

        List<Session> sessions = new ArrayList<>();
        for (byte[] keyBytes : keyBytesSet) {
            byte[] valueBytes = redisTemplate.execute((RedisCallback<byte[]>) connection ->
                    connection.get(keyBytes)
            );
            if (valueBytes != null) {
                // 使用自定义工具类反序列化
                Session session = (SimpleSession) JDKSerializeUtils.deserialize(valueBytes);
                sessions.add(session);
            }
        }
        return sessions;
    }

    // ------------------------------ 私有工具方法 ------------------------------

    /**
     * 构建Session的Redis Key（字符串形式）
     */
    private String buildKey(Serializable sessionId) {
        String key = ShiroConstant.SHIRO_SESSION_KEY + sessionId;
        log.info("当前Session Key: {}", key);
        return key;
    }

    /**
     * 构建Session的Redis Key（字节数组形式）
     */
    private byte[] buildKeyBytes(Serializable sessionId) {
        return keySerializer.serialize(buildKey(sessionId));
    }

    /**
     * 构建用于模糊查询的Key前缀（字节数组形式）
     */
    private byte[] buildKeyPatternBytes() {
        return keySerializer.serialize(ShiroConstant.SHIRO_SESSION_KEY + "*");
    }

    /**
     * 保存Session（使用自定义JDK序列化工具类）
     */
    private void saveSession(Serializable sessionId, Session session) {
        byte[] keyBytes = buildKeyBytes(sessionId);
        // 使用自定义工具类序列化Session
        byte[] valueBytes = JDKSerializeUtils.serialize(session);
        redisTemplate.execute((RedisCallback<Void>) connection -> {
            connection.set(keyBytes, valueBytes);
            // 设置过期时间（30分钟，单位：秒）
            connection.expire(keyBytes, 30 * 60);
            return null;
        });
    }

    /**
     * 读取Session（使用自定义JDK序列化工具类）
     */
    private Session getSession(Serializable sessionId) {
        byte[] keyBytes = buildKeyBytes(sessionId);
        return redisTemplate.execute((RedisCallback<Session>) connection -> {
            byte[] valueBytes = connection.get(keyBytes);
            if (valueBytes == null) {
                return null;
            }
            // 校验是否为JDK序列化数据（JDK序列化开头标识：AC ED 00 05）
            if (valueBytes.length >= 4 &&
                    valueBytes[0] == (byte) 0xAC &&
                    valueBytes[1] == (byte) 0xED &&
                    valueBytes[2] == (byte) 0x00 &&
                    valueBytes[3] == (byte) 0x05) {
                // 使用自定义工具类反序列化
                return (SimpleSession) JDKSerializeUtils.deserialize(valueBytes);
            } else {
                log.warn("发现非JDK序列化数据，删除Key: {}", new String(keyBytes));
                connection.del(keyBytes);
                return null;
            }
        });
    }

    /**
     * 刷新Session过期时间
     */
    private void refreshSessionExpire(Serializable sessionId) {
        byte[] keyBytes = buildKeyBytes(sessionId);
        redisTemplate.execute((RedisCallback<Void>) connection -> {
            connection.expire(keyBytes, 30 * 60); // 30分钟过期
            return null;
        });
    }
}
